﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;

namespace DataAchive.UserControls
{
    /// <summary>
    /// DateTimePick.xaml 的交互逻辑
    /// </summary>
    public partial class DateTimePick : UserControl
    {
        #region 依赖属性
        /// <summary>
        /// 时间
        /// </summary>
        public string TimeValueStr
        {
            get { return (string)GetValue(TimeValueStrProperty); }
            set { SetValue(TimeValueStrProperty, value); }
        }

        public static readonly DependencyProperty TimeValueStrProperty =
            DependencyProperty.Register("TimeValueStr", typeof(string), typeof(DateTimePick), new PropertyMetadata(""));

        /// <summary>
        /// 时间
        /// </summary>
        public DateTime TimeValue
        {
            get { return (DateTime)GetValue(TimeValueProperty); }
            set { SetValue(TimeValueProperty, value); }
        }

        public static readonly DependencyProperty TimeValueProperty =
            DependencyProperty.Register("TimeValue", typeof(DateTime), typeof(DateTimePick), new PropertyMetadata(DateTime.Now, (sender, e) =>
            {
                var dp = sender as DateTimePick;
                if (dp == null) return;
                dp.GetTime();
            }));

        public bool MonthShow
        {
            get { return (bool)GetValue(MonthShowProperty); }
            set { SetValue(MonthShowProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MonthShow.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MonthShowProperty =
            DependencyProperty.Register("MonthShow", typeof(bool), typeof(DateTimePick), new PropertyMetadata(true));



        public bool DayShow
        {
            get { return (bool)GetValue(DayShowProperty); }
            set { SetValue(DayShowProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DayShow.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DayShowProperty =
            DependencyProperty.Register("DayShow", typeof(bool), typeof(DateTimePick), new PropertyMetadata(true));



        public bool TimeShow
        {
            get { return (bool)GetValue(TimeShowProperty); }
            set { SetValue(TimeShowProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TimeShow.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TimeShowProperty =
            DependencyProperty.Register("TimeShow", typeof(bool), typeof(DateTimePick), new PropertyMetadata(true));



        #endregion

        List<RadioButton> days = new List<RadioButton>();

        private void GetTime()
        {
            if (TimeValue != null)
            {
                //开始时间
                cmb_Year.SelectedValue = TimeValue.Year;
                cmb_Mon.SelectedValue = TimeValue.Month;
                cmb_SelectionChanged(null, null);
                RadioButton temp = days.FirstOrDefault(t => t.Content.ToString() == TimeValue.Day.ToString());
                if (temp != null)
                {
                    temp.IsChecked = true;
                }
                text_Hour.Text = TimeValue.Hour.ToString().PadLeft(2, '0');
                text_Min.Text = TimeValue.Minute.ToString().PadLeft(2, '0');
                text_Second.Text = TimeValue.Second.ToString().PadLeft(2, '0');
                string format = "yyyy";
                if (!MonthShow)
                {
                    DayShow = false;
                    TimeShow = false;
                }
                else
                    format += "-MM";

                if (!DayShow)
                    TimeShow = false;
                else
                    format += "-dd";

                if (TimeShow)
                    format += " HH:mm:ss";
                TimeValueStr = TimeValue.ToString(format);
            }
        }


        public DateTimePick()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            InitCmb();
            TimeValue = DateTime.Now;
        }

        private void InitCmb()
        {
            List<int> YearList = new List<int>();
            for (int i = 1990; i < DateTime.Now.Year + 15; i++)
            {
                YearList.Add(i);
            }
            cmb_Year.ItemsSource = YearList;
            List<int> MonList = new List<int>();
            for (int i = 1; i < 13; i++)
            {
                MonList.Add(i);

            }
            cmb_Mon.ItemsSource = MonList;
        }

        private void btn_Clear_Click(object sender, RoutedEventArgs e)
        {
            TimeValue = DateTime.Now;
        }

        private void btn_Sure_Click(object sender, RoutedEventArgs e)
        {
            btn_ChoseTime.IsChecked = false;
        }

        private void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmb_Year.SelectedValue != null && cmb_Mon.SelectedValue != null)
            {
                days.Clear();
                StartWrap.Children.Clear();

                DateTime firstOfMonth = new DateTime((int)cmb_Year.SelectedValue, (int)cmb_Mon.SelectedValue, 1);
                //周1-周7
                int dayOfWeek = ((int)firstOfMonth.DayOfWeek + 6) % 7 + 1;
                //本月1号前面有几天
                int beforDay = Math.Abs(1 - dayOfWeek);
                for (int i = beforDay; i > 0; i--)
                {
                    RadioButton daybutton = new RadioButton();
                    daybutton.Content = (firstOfMonth.AddDays(-i).Day).ToString().PadLeft(2, '0');
                    daybutton.BorderBrush = Brushes.Gray;
                    StartWrap.Children.Add(daybutton);
                    days.Add(daybutton);
                }

                int SelectedMon = (int)cmb_Mon.SelectedValue;
                switch (SelectedMon)
                {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        for (int i = 1; i < 32; i++)
                        {
                            RadioButton daybutton = new RadioButton();
                            daybutton.Content = i.ToString().PadLeft(2, '0');
                            daybutton.Click += Start_Daybutton_Click;
                            StartWrap.Children.Add(daybutton);
                            days.Add(daybutton);
                        }
                        break;
                    case 2:
                        if (cmb_Year.SelectedValue != null)
                        {
                            int temp = int.Parse(cmb_Year.SelectedValue.ToString());
                            if (temp % 4 == 0)
                            {
                                if (temp % 100 == 0)
                                {
                                    if (temp % 400 == 0)
                                    {
                                        for (int i = 1; i < 30; i++)
                                        {
                                            RadioButton daybutton = new RadioButton();
                                            daybutton.Content = i.ToString().PadLeft(2, '0');
                                            daybutton.Click += Start_Daybutton_Click;
                                            StartWrap.Children.Add(daybutton);
                                            days.Add(daybutton);
                                        }
                                    }
                                    else
                                    {
                                        for (int i = 1; i < 29; i++)
                                        {
                                            RadioButton daybutton = new RadioButton();
                                            daybutton.Content = i.ToString().PadLeft(2, '0');
                                            daybutton.Click += Start_Daybutton_Click;
                                            StartWrap.Children.Add(daybutton);
                                            days.Add(daybutton);
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = 1; i < 30; i++)
                                    {
                                        RadioButton daybutton = new RadioButton();
                                        daybutton.Content = i.ToString().PadLeft(2, '0');
                                        daybutton.Click += Start_Daybutton_Click;
                                        StartWrap.Children.Add(daybutton);
                                        days.Add(daybutton);
                                    }
                                }
                            }
                            else
                            {
                                for (int i = 1; i < 29; i++)
                                {
                                    RadioButton daybutton = new RadioButton();
                                    daybutton.Content = i.ToString().PadLeft(2, '0');
                                    daybutton.Click += Start_Daybutton_Click;
                                    StartWrap.Children.Add(daybutton);
                                    days.Add(daybutton);
                                }
                            }
                        }
                        break;
                    default:
                        for (int i = 1; i < 31; i++)
                        {
                            RadioButton daybutton = new RadioButton();
                            daybutton.Content = i.ToString().PadLeft(2, '0');
                            daybutton.Click += Start_Daybutton_Click;
                            StartWrap.Children.Add(daybutton);
                            days.Add(daybutton);
                        }
                        break;
                }

                DateTime lastOfMonth = firstOfMonth.AddMonths(1).AddDays(-1);
                //周1-周7
                int lastDayOfWeek = ((int)lastOfMonth.DayOfWeek + 6) % 7 + 1;
                //本月最后一天后有几天
                int laterDay = Math.Abs(7 - lastDayOfWeek);
                for (int i = 1; i <= laterDay; i++)
                {
                    RadioButton daybutton = new RadioButton();
                    daybutton.Content = i.ToString().PadLeft(2, '0');
                    daybutton.BorderBrush = Brushes.Gray;
                    StartWrap.Children.Add(daybutton);
                    days.Add(daybutton);
                }

                try
                {
                    TimeValue = new DateTime(int.Parse(cmb_Year.SelectedValue.ToString()), int.Parse(cmb_Mon.SelectedValue.ToString()), TimeValue.Day, TimeValue.Hour, TimeValue.Minute, TimeValue.Second);
                }
                catch (Exception exx)
                {

                }
            }
        }

        private void Start_Daybutton_Click(object sender, RoutedEventArgs e)
        {
            RadioButton temp = sender as RadioButton;
            if (temp != null)
            {
                TimeValue = new DateTime(TimeValue.Year, TimeValue.Month, int.Parse(temp.Content.ToString()), TimeValue.Hour, TimeValue.Minute, TimeValue.Second);
            }
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9]+");
            e.Handled = re.IsMatch(e.Text);
        }

        private void Text_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox temp = sender as TextBox;
            if (temp != null)
            {
                if (string.IsNullOrEmpty(temp.Text))
                {
                    return;
                }
                switch (temp.Name)
                {
                    case "text_StartHour":
                        if (int.Parse(temp.Text) < 0)
                        {
                            temp.Text = "0";
                        }
                        else if (int.Parse(temp.Text) > 23)
                        {
                            temp.Text = "23";
                        }
                        break;
                    case "text_StartMin":
                        if (int.Parse(temp.Text) < 0)
                        {
                            temp.Text = "0";
                        }
                        else if (int.Parse(temp.Text) > 59)
                        {
                            temp.Text = "59";
                        }
                        break;
                    case "text_StartSecond":
                        if (int.Parse(temp.Text) < 0)
                        {
                            temp.Text = "0";
                        }
                        else if (int.Parse(temp.Text) > 59)
                        {
                            temp.Text = "59";
                        }
                        break;
                    default:
                        break;
                }
                TimeValue = new DateTime(TimeValue.Year, TimeValue.Month, TimeValue.Day, int.Parse(text_Hour.Text), int.Parse(text_Min.Text), int.Parse(text_Second.Text));
                temp.Text = temp.Text.PadLeft(2, '0');
            }
        }



    }
    public class DateToString : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string timeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (value != null)
            {
                try
                {
                    DateTime dateTime = (DateTime)value;

                    timeStr = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                }
                catch
                {
                    timeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }
            }
            return timeStr;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime dateTime = DateTime.Now;
            if (value != null)
            {
                try
                {
                    string timeStr = (string)value;

                    dateTime = System.Convert.ToDateTime(timeStr);
                }
                catch
                {
                    dateTime = DateTime.Now;
                }
            }
            return dateTime;
        }
    }
}
